<template>
  <div class="default-main ba-table-box">
    <!-- 表格顶部菜单 -->
    <TableHeader
      :buttons="['refresh', 'columnDisplay', 'comSearch']"
      :quick-search-placeholder="placeholder"
      @action="baTable.onTableHeaderAction"
    />
    <!-- 要使用`el-table`组件原有的属性，直接加在Table标签上即可 -->
    <Table ref="tableRef" @action="baTable.onTableAction" />
    <!-- 表单 -->
    <!-- <PopupForm v-if="baTable.form.operate ? true : false" /> -->
  </div>
</template>
<script lang="ts" setup>
import {
  ref,
  provide,
  onMounted,
  reactive,
  onBeforeUnmount,
  markRaw,
} from "vue";
import baTableClass from "@/utils/baTable";
import { baTableApi, operatorShowOff } from "@/utils/common"; // 导入表格api方法生成器
import Table from "@/components/table/index.vue";
import TableHeader from "@/components/table/header/index.vue";
import { ProductionWorkOrder } from "@/api/backend/index";
// import PopupForm from "./components/orderPopupForm.vue";
import { useRoute, useRouter } from "vue-router";
import TagVue from "./tag.vue";
import TagSearch from "@/components/tagSearch/index.vue";
import useCurrentInstance from "@/utils/useCurrentInstance";
import type { TableRow, TableColumn } from "@/utils/baTable"; //表格列行类型
import { useNavTabs } from "@/store/navTabs";
import { getDictData } from "@/utils/common";
import { useDictionary } from "@/store/backend/tool/dictionary";
import { useProductionPlan } from "@/store/backend/ProductionPlan/plan";
import { useBomM } from "@/store/backend/BomM/bomM";
import { useBomDict } from "@/store/backend/BomM/bomDict";
import { useFactoryStation } from "@/store/backend/FactoryM/stationInfo";
import { useProductionWorkOrder } from "@/store/backend/ProductionPlan/workOrder";
import { useFactoryEquipment } from "@/store/backend/FactoryM/equipmentUnit";
import OrderTag from "./orderState.vue"

const placeholder = ref<string>("模糊搜索");
const tableRef = ref();
const route = useRoute();
const router = useRouter();
const navTabs = useNavTabs();
const dictionary = useDictionary();
const plan = useProductionPlan();
const bom = useBomM();
const bomD = useBomDict();
const station = useFactoryStation();
const planOrder = useProductionWorkOrder();
const equipment = useFactoryEquipment();

//全局事件总线
const { proxy } = useCurrentInstance();

const state: {} = reactive({});

//字段显隐记忆功能
const filedShowOff = (filter: any) => {
  if ((navTabs as any).columnDisplayStoreMap) {
    return (navTabs as any).columnDisplayStoreMap.get(
      route.path + "/" + filter
    );
  }
  return true;
};
// 每页个数记忆功能
const pageSizeKeep = () => {
  if ((navTabs as any).pageSizeMap) {
    return (navTabs as any).pageSizeMap.get(route.path + ProductionWorkOrder)
      ? (navTabs as any).pageSizeMap.get(route.path + ProductionWorkOrder)
      : 10;
  }
  return 10;
};

const baTable = new baTableClass(
  new baTableApi(ProductionWorkOrder), //this.api = api部门管理
  {
    expandAll: true,
    pk: "id",
    column: [
      { type: "selection", align: "center", operator: false },
      {
        show: filedShowOff("id"),
        label: "工单ID",
        prop: "id",
        align: "left",
        operatorPlaceholder: "模糊搜索",
      },
      {
        show: filedShowOff("code"),
        label: "计划号",
        prop: "code",
        align: "left",
        operatorPlaceholder: "模糊搜索",
      },
      {
        show: filedShowOff("name"),
        label: "批次号",
        prop: "name",
        align: "left",
        operatorPlaceholder: "模糊搜索",
      },
      {
        show: filedShowOff("state"),
        label: "工单状态",
        prop: "state",
        align: "left",
        render: "customRender",
        customRender: markRaw(OrderTag),
        comSearchRender: "customRender",
        comSearchCustomRender: markRaw(TagSearch),
      },
      {
        show: filedShowOff("productCode"),
        label: "物料编码",
        prop: "productCode",
        align: "left",
        operatorPlaceholder: "模糊搜索",
      },
      {
        show: filedShowOff("productName"),
        label: "物料名称",
        prop: "productName",
        align: "left",
        operatorPlaceholder: "模糊搜索",
      },
      {
        show: filedShowOff("materialType"),
        label: "产品类型",
        prop: "materialType",
        align: "left",
        operatorPlaceholder: "模糊搜索",
      },
      {
        show: filedShowOff("workshopName"),
        label: "车间",
        prop: "workshopName",
        align: "left",
        operatorPlaceholder: "模糊搜索",
      },
      {
        show: filedShowOff("equipmentCode"),
        label: "设备编码",
        prop: "equipmentCode",
        align: "left",
        operatorPlaceholder: "模糊搜索",
      },
      {
        show: filedShowOff("personId"),
        label: "人员id",
        prop: "personId",
        align: "left",
        operator: false,
      },
      {
        show: filedShowOff("planQuantity"),
        label: "计划数",
        prop: "planQuantity",
        align: "left",
        operator: false,
        render: "customTemplate",
        customTemplate: (row: TableRow, field: TableColumn, value: any) => {
          return (
            "<p>" +
            row.planQuantity * (row.perUsage ? row.perUsage : 1) +
            "</p>"
          );
        },
      },
      {
        show: filedShowOff("productQuantity"),
        label: "投产数",
        prop: "productQuantity",
        align: "left",
        operator: false,
      },
      {
        show: filedShowOff("perUsage"),
        label: "每用量",
        prop: "perUsage",
        align: "left",
        operator: false,
      },
      {
        show: filedShowOff("productRate"),
        label: "加工进度%",
        prop: "productRate",
        align: "left",
        operator: false,
      },
      {
        show: filedShowOff("productType"),
        label: "生产类型",
        prop: "productType",
        align: "left",
        render: "customRender",
        customRender: markRaw(OrderTag),
        operator: false,
      },
      {
        show: filedShowOff("startTime"),
        label: "计划开始时间",
        prop: "startTime",
        align: "center",
        render: "datetime",
      },
      {
        show: filedShowOff("endTime"),
        label: "计划结束时间",
        prop: "endTime",
        align: "center",
        render: "datetime",
      },
      {
        show: filedShowOff("endTime"),
        label: "实际开始时间",
        prop: "actualStartTime",
        align: "center",
        render: "datetime",
      },
      {
        show: filedShowOff("endTime"),
        label: "实际结束时间",
        prop: "actualEndTime",
        align: "center",
        render: "datetime",
      },
      {
        show: filedShowOff("deliverDate"),
        label: "交付日期",
        prop: "deliverDate",
        align: "center",
        // render: "datetime",
        operator: false,
      },
      {
        show: filedShowOff("priority"),
        label: "优先级",
        prop: "priority",
        align: "center",
        render: "customRender",
        customRender: markRaw(OrderTag),
        comSearchRender: "customRender",
        comSearchCustomRender: markRaw(TagSearch),
      },
      {
        show: false,
        label: "操作",
        align: "center",
        operator: false,
        render: "buttons",
        fixed: "right",
        width: "150",
        buttons: [
          {
            render: "tipButton",
            name: "revoke",
            title: "撤销派工",
            text: "",
            type: "danger",
            icon: "iconfont icon-undo",
            class: "table-row-edit",
            disabledTip: false,
            // 按钮是否显示，请返回布尔值
            display: (row: TableRow, field: TableColumn) => {
              return true;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
          {
            render: "dropdown",
            name: "dropdown",
            title: "更多",
            text: "",
            type: "primary",
            icon: "iconfont icon-xinzeng",
            class: "table-row-edit",
            disabledTip: false,
            // 按钮是否显示，请返回布尔值
            display: (row: TableRow, field: TableColumn) => {
              return true;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {
              dropdown: [
                {
                  name: "edit",
                  title: "人员",
                  icon: "el-icon-Avatar",
                  class: "table-row-dropdown",
                },
                {
                  name: "edit",
                  title: "设备",
                  icon: "iconfont icon-shebeiguanli1",
                  class: "table-row-dropdown",
                },
              ],
            },
          },
        ],
      },
    ],
    filter: {
      equipmentCode: equipment.single.equipmentCode,
      pageSize: pageSizeKeep(),
    },
    extend: {
      maxHeight: 580,
    },
  },
  {},
  {}
);

//获取计划状态/是否暂停的字典
const getMenuStatus = () => {
  if (
    JSON.stringify(dictionary.moreTags) == "{}" ||
    !JSON.stringify(dictionary.moreTags["productType"])
  ) {
    dictionary.getDictInfo("sys_plan_producttype").then((res: any) => {
      dictionary.moreTags["productType"] = getDictData(res);
      plan.options["productType"] = res;
      console.log("获取生产类型的字典", dictionary.moreTags);
    });
  }
  if (
    JSON.stringify(dictionary.moreTags) == "{}" ||
    !JSON.stringify(dictionary.moreTags["priority"])
  ) {
    dictionary.getDictInfo("sys_plan_priority").then((res: any) => {
      dictionary.moreTags["priority"] = getDictData(res);
      plan.options["priority"] = res;
      console.log("获取优先级的字典", dictionary.moreTags);
    });
  }
  if (
    JSON.stringify(dictionary.moreTags) == "{}" ||
    !JSON.stringify(dictionary.moreTags["isProduct"])
  ) {
    dictionary.getDictInfo("sys_plan_isproduct").then((res: any) => {
      dictionary.moreTags["isProduct"] = getDictData(res);
      plan.options["isProduct"] = res;
      console.log("获取是否排产的字典", dictionary.moreTags);
    });
  }
  if (
    JSON.stringify(dictionary.moreTags) == "{}" ||
    !JSON.stringify(dictionary.moreTags["state"])
  ) {
    dictionary.getDictInfo("sys_workorder_state").then((res: any) => {
      dictionary.moreTags["state"] = getDictData(res);
      plan.options["state"] = res;
      console.log("获取是否排产的字典", dictionary.moreTags);
    });
  }
};
getMenuStatus();

//跳转详情页
const infoButtonClick = (id: number, row: any) => {
  console.log("id", id, "row", row);
  planOrder.$patch((state) => {
    state.single = row;
    state.planId = row.id;
  });
  router.push({
    path: "/admin/ProductionWorkOrder/detail",
    query: { materialCode: row.productCode, materialType: row.materialType },
  });
};

planOrder.$subscribe((state: any) => {
  const storeOrder = (data: any[]) => {
    for (let i = 0, len = data.length; i < len; i++) {
      if (data[i].key === "getOrder") {
        return true;
      }
    }
    return false;
  };
  if (storeOrder(state.events)) {
    baTable.getList(ProductionWorkOrder);
  }
});

//派工
const toggleDispatch = (id: number, row: any) => {
  proxy.eventBus.emit("workOrderDrawer");
};

onMounted(() => {
  //全局事件总线
  const { proxy } = useCurrentInstance();
  //将table的ref给到table类
  baTable.table.ref = tableRef.value;
  baTable.mount();
  baTable.getList(ProductionWorkOrder);
  /**
   * 表格内的按钮响应
   * @param name 按钮name
   * @param row 被操作行数据
   */

  proxy.eventBus.on(
    "onTableButtonClick",
    (data: { name: string; row: TableRow }) => {
      switch (data.name) {
        case "wander":
          //流转卡
          break;
        case "feedback":
          //问题反馈
          break;
        case "info":
          //详情页面
          infoButtonClick(
            (data.row as TableRow)[baTable.table.pk!],
            data.row as any
          );
          break;
        case "dispatch":
          //派工
          toggleDispatch(
            (data.row as TableRow)[baTable.table.pk!],
            data.row as any
          );
          break;
      }
    }
  );
});
onBeforeUnmount(() => {});
// 实例化表格后，将 baTable 的实例提供给上下文
provide("baTable", baTable);
provide("dictionary", dictionary);
provide("plan", plan);
provide("bom", bom);
provide("bomD", bomD);
provide("station", station);
</script>
<style lang="scss" scoped>
.default-main {
  margin: 0px !important;
  margin-bottom: 30px !important;
}
</style>
